package dev.android.yeqh.iask_sina;

import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListView;
import dev.android.yeqh.iask_sina.adapter.SearchResultAdapter;
import dev.android.yeqh.iask_sina.common.Constants;
import dev.android.yeqh.iask_sina.common.NetTask;
import dev.android.yeqh.iask_sina.common.Utils;
import dev.android.yeqh.iask_sina.model.NetTaskParam;
import dev.android.yeqh.iask_sina.model.cidianItem;

public class SearchResultActivity extends BaseActivity {
	EditText edtKeyword = null;
	ListView lstSearchResult = null;
	SearchResultAdapter adapter = null;
	boolean isWording = true;
	boolean isEnd = false;
	int currentPage = 0;
	String key = "";
	OnScrollListener scrollListener = new OnScrollListener() {
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			
		}
		
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (!isWording && !isEnd && firstVisibleItem + visibleItemCount + 2 > totalItemCount) {
				isWording = true;
				currentPage++;
				new NetTask(SearchResultActivity.this, true).execute(new NetTaskParam(Constants.TYPE_SEARCH_RESULT, new Object[] {key, currentPage}));
			}
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_result);
        
        edtKeyword = (EditText)findViewById(R.id.txt_keyword);
        lstSearchResult = (ListView)findViewById(R.id.lst_result);
        adapter = new SearchResultAdapter(this, R.layout.item_result);
        lstSearchResult.setAdapter(adapter);
        lstSearchResult.setOnScrollListener(scrollListener);
        
        key = getIntent().getStringExtra("keyword");
        new NetTask(this, true).execute(new NetTaskParam(Constants.TYPE_SEARCH_RESULT, new Object[] {key, 0}));
    }
    
    public void search(View view) {
    	key = edtKeyword.getText().toString();
    	adapter.clearItems();
    	new NetTask(this, true).execute(new NetTaskParam(Constants.TYPE_SEARCH_RESULT, new Object[] {key, 0}));
    }
    
    @SuppressWarnings("unchecked")
	@Override
    public void updateUI(Object result) {
    	try {
    		if (result instanceof Exception) {
    			Utils.showMessage(this, (Exception)result);
    			return;
    		}
    		List<cidianItem> results = (List<cidianItem>)result;
    		adapter.setItems(results);
    		adapter.notifyDataSetChanged();
    		if (results.size() < 10) {
    			isEnd = true;
    		}
    	} catch (Exception e) {
			Utils.showMessage(this, e);
		}
    	isWording = false;
    	super.updateUI(result);
    }
}